package com.cloudcross.ssp.web.advertiser.main.ad;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.ArrayUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.cloudcross.ssp.base.utils.freemarker.FreemarkerTemplateProcessor;
import com.cloudcross.ssp.base.web.SimpleController;
import com.cloudcross.ssp.common.Config;
import com.cloudcross.ssp.common.consts.Status;
import com.cloudcross.ssp.common.utils.Common;
import com.cloudcross.ssp.common.utils.LangUtil;
import com.cloudcross.ssp.common.utils.Pager;
import com.cloudcross.ssp.listener.UploadListener;
import com.cloudcross.ssp.model.Account;
import com.cloudcross.ssp.model.BannerTemplate;
import com.cloudcross.ssp.model.Log;
import com.cloudcross.ssp.model.Size;
import com.cloudcross.ssp.service.IBannerTemplateService;
import com.cloudcross.ssp.service.ILogService;
import com.cloudcross.ssp.service.ISizeService;

/**
 * 创意中心(创意模板)功能相关页面。
 *
 * @author djp
 */
@Controller
@RequestMapping("/advertiser/main/ad/banner-template")
public class BannerTemplateController extends SimpleController {

    private Logger LOG = LogManager.getLogger(getClass());

    @Autowired
    private IBannerTemplateService bannerTemplateService;
    @Autowired
    private FreemarkerTemplateProcessor templateProcessor;
    @Autowired
    private ISizeService sizeService;
    @Autowired
    Config config;
    @Autowired
    private ILogService logService;

    // 文件系统可上传的文件后缀集合
    private static Set<String> noStuffixSet = new HashSet<String>();

    // 初始化可上传文件后缀
    static {
        noStuffixSet.add("jpg");
        noStuffixSet.add("gif");
        noStuffixSet.add("png");
        noStuffixSet.add("swf");
    }

    private static UploadListener uploadListener = UploadListener.getInstance();

    /**
     * 显示list方法。 根据创意尺寸，创意类型，状态显示相应的素材。 根据搜索框输入的姓名搜索显示相应的素材列表。
     */
    @RequestMapping("/list")
    public String list(Model model, @RequestParam Map<String, Object> paramMap, @RequestParam(defaultValue = "1") int page) {
        model.addAttribute("width", paramMap.get("width"));
        model.addAttribute("height", paramMap.get("height"));
        model.addAttribute("type", paramMap.get("type"));
        model.addAttribute("status", paramMap.get("status"));
        model.addAttribute("advertiserId", paramMap.get("advertiserId"));
        Account loginUser = getLoginUser();
        Long agentId = loginUser.getAgentId();
        paramMap.put("agentId", agentId);
        Long advertiserId = loginUser.getAdvertiserId();
        // 如果账号关联广告主，加入广告主过滤条件
        if (!paramMap.containsKey(advertiserId)) {

            if (advertiserId != 0) {
                paramMap.put("advertiserId", advertiserId);
            }
        }
        // 根据广告策略名模糊统计符合条件的策略总数
        int totalRow = bannerTemplateService.countByParams2(paramMap);
        // 查询符合条件的广告策略
        Pager pager = new Pager();
        pager.setPage(page);
        pager.setTotalRow(totalRow);
        // 获取创意的列表
        List<BannerTemplate> bannerTemplateList = bannerTemplateService.findByParams2(paramMap, pager);
        // 获取尺寸的列表
        List<Size> sizeList = sizeService.findAllSize();
        model.addAllAttributes(paramMap);
        model.addAttribute("pager", pager);
        model.addAttribute("bannerTemplateList", bannerTemplateList);
        model.addAttribute("sizeList", sizeList);
        return page("list");
    }

    /**
     * 单个或者批量启用功能。 删除将status更新为0值
     *
     * @return 成功则返回"ok"
     */
    @RequestMapping("/enable")
    public @ResponseBody
    String enable(HttpServletRequest request, Long[] id) {
        // 输出log信息，控制台打印出id的值
        LOG.debug("Args's value: id=" + Arrays.toString(id));
        // 将id转为List<Long>类型传入updateStatus函数
        if (ArrayUtils.isNotEmpty(id)) {
            bannerTemplateService.updateStatus(LangUtil.array2List(id), Status.enable.value);
            for (int i = 0; i < id.length; i++) {
                Log log = new Log();
                // 对应模块，这里应该是投放模块
                log.setModule("BannerTemplate");
                // 对应的表名，这里是t_adgroup
                log.setTableName("t_banner_template");
                // 对应的投放id
                log.setRecordId(id[i]);
                // 对应的操作类型
                log.setActionType("启用");
                // 变更详情
                log.setAction("启用了素材模板:" + id[i]);
                // 下面这几个字段目前后端数据没有得到。所以仅作测试用！
                log.setActionTime("100");
                log.setAccountId(new Long(getLoginUser().getId()));
                log.setUserIp(Common.toIpAddr(request));
                log.setAccountName(getLoginUser().getAccountName());
                logService.add(log);
            }
        }
        return OK;
    }

    /**
     * 单个或者批量禁用功能。 删除将status更新为1值
     *
     * @return 成功则返回"ok"
     */
    @RequestMapping("/disable")
    public @ResponseBody
    String disable(HttpServletRequest request, Long[] id) {
        // 输出log信息，控制台打印出id的值
        LOG.debug("Args's value: id=" + Arrays.toString(id));
        // 将id转为List<Long>类型传入updateStatus函数
        if (ArrayUtils.isNotEmpty(id)) {
            bannerTemplateService.updateStatus(LangUtil.array2List(id), Status.disable.value);
            for (int i = 0; i < id.length; i++) {
                Log log = new Log();
                // 对应模块，这里应该是投放模块
                log.setModule("BannerTemplate");
                // 对应的表名，这里是t_adgroup
                log.setTableName("t_banner_template");
                // 对应的投放id
                log.setRecordId(id[i]);
                // 对应的操作类型
                log.setActionType("停用");
                // 变更详情
                log.setAction("停用了素材模板:" + id[i]);
                // 下面这几个字段目前后端数据没有得到。所以仅作测试用！
                log.setActionTime("100");
                log.setAccountId(new Long(getLoginUser().getId()));
                log.setUserIp(Common.toIpAddr(request));
                log.setAccountName(getLoginUser().getAccountName());
                logService.add(log);
            }
        }
        return OK;
    }

    @RequestMapping("/update")
    public String update(Model model, @RequestParam Long bannerTemplateId, @RequestParam(defaultValue = "1") int page) {
        Map<String, Object> condition = new HashMap<String, Object>();
        // 查询总行数
        condition.put("tableName", "t_banner_template");
        condition.put("recordId", bannerTemplateId);
        int totalRow = logService.findLogCountByCondition(condition);
        Pager pager = new Pager();
        pager.setPage(page);
        pager.setTotalRow(totalRow);
        List<Log> logList = logService.findLogByCondition(condition, pager);
        model.addAttribute("pager", pager);
        model.addAttribute("logList", logList);
        model.addAttribute("bannerTemplateId", bannerTemplateId);
        return page("update");
    }

    /**
     * 单个或者批量删除功能。 删除将status更新为-1值
     *
     * @return 成功则返回"ok"
     */
    @RequestMapping("/delete")
    public @ResponseBody
    String delete(Long[] id, HttpServletRequest request) {
        // 将id转为List<Long>类型传入updateStatus函数
        if (ArrayUtils.isNotEmpty(id)) {
            bannerTemplateService.deleteUpdata(LangUtil.array2List(id), Status.delete.value);
            for (int i = 0; i < id.length; i++) {
                Log log = new Log();
                // 对应模块，这里应该是投放模块
                log.setModule("BannerTemplate");
                // 对应的表名，这里是t_adgroup
                log.setTableName("t_banner_template");
                // 对应的投放id
                log.setRecordId(id[i]);
                // 对应的操作类型
                log.setActionType("删除");
                // 变更详情
                log.setAction("删除了素材模板:" + id[i]);
                // 下面这几个字段目前后端数据没有得到。所以仅作测试用！
                log.setActionTime("100");
                log.setAccountId(new Long(getLoginUser().getId()));
                log.setUserIp(Common.toIpAddr(request));
                log.setAccountName(getLoginUser().getAccountName());
                logService.add(log);
            }
        }
        return OK;
    }

    /**
     * 修改素材名字功能。 传入素材id和要修改的name
     *
     * @return 成功则返回"ok"
     */
    @RequestMapping("/alterName")
    public @ResponseBody
    String alterName(@RequestParam int id, @RequestParam String name) {
        // 将id和name写入Map,ad-template.sql.xml读出使用
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("name", name);
        paramMap.put("id", id);
        bannerTemplateService.alterName(paramMap);
        return OK;
    }

    @RequestMapping(value = "/upload")
    public @ResponseBody
    String upload(Model model, HttpServletRequest request, Long advertiserId) throws IOException {
        String uploadName;
        String resetName;
        String fileType;
        // 文件路径
        String path;
        // 缩略图路径
        String pathSmall;
        String responseStr = "null";
        int width;
        int height;
        Account loginUser = getLoginUser();
        Long agentId = loginUser.getAgentId();
        Long operatorId = loginUser.getOperatorId();
        if (request.getMethod() == "POST") {
            // 转 换成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> fileMap = multiRequest.getFileMap();
            try {
                // 取得request中的所有文件名
                for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                    MultipartFile file = entity.getValue();
                    BannerTemplate bannerTemplate = new BannerTemplate();
                    if (file != null && file.getSize() < 1024 * 2 * 1000) {
                        // 取得当前上传文件的文件名称(不加路径)
                        uploadName = file.getOriginalFilename();
                        resetName = bannerTemplateService.resetName(uploadName);
                        // 获取文件类型
                        fileType = uploadName.substring(uploadName.lastIndexOf(".") + 1);
                        // 判断文件类型
                        if (!noStuffixSet.contains(fileType)) {
                            return "不支持此文件类型";
                        }
                        // 如果名称不为“”,说明该文件存在，否则说明该文件不存在
                        if (uploadName.trim() != "") {
                            // 处理上传文件路径
                            path = bannerTemplateService.getLocalFilePath(resetName);
                            File localFile = new File(path);
                            // 上传目录不存在，则新建目录
                            if (!localFile.getParentFile().exists()) {
                                localFile.getParentFile().mkdirs();
                            }
                            // 生成上传文件
                            file.transferTo(localFile);
                            int filetype = bannerTemplateService.judgeType(fileType);
                            if (filetype == 2) {
                                // 取上传图片的宽高
                                BufferedImage image = ImageIO.read(new FileInputStream(path));
                                width = image.getWidth();
                                height = image.getHeight();
                                // 匹配广告位
                                bannerTemplate = bannerTemplateService.suitSize(width, height, bannerTemplate);
                            } else {
                                bannerTemplate.setHeight(0l);
                                bannerTemplate.setWidth(0l);
                                bannerTemplate.setRheight(0l);
                                bannerTemplate.setRwidth(0l);
                            }
                            // 图片匹配
                            if (bannerTemplate == null) {
                                return "图片尺寸错啦！！";
                            }
                            // 取上传文件父级目录
                            String absolutePath = localFile.getParentFile().getAbsolutePath();
                            // 生成缩略图路径名
                            pathSmall = absolutePath.concat(File.separator).concat("small_").concat(resetName);
                            // 生成缩略图
                            bannerTemplateService.compressPicture(localFile, pathSmall, 150, 60);
                            // 设置文件上传路径
                            bannerTemplate.setPath(bannerTemplateService.replacePath(path));
                            // 设置缩略图文件路径
                            bannerTemplate.setPathSmall(bannerTemplateService.replacePath(pathSmall));
                            bannerTemplate.setName(uploadName);
                            bannerTemplate.setType(bannerTemplateService.judgeType(fileType));
                            bannerTemplate.setStatus(0);
                            bannerTemplate.setAdvertiserId(advertiserId);
                            bannerTemplate.setAgentId(agentId);
                            bannerTemplate.setOperatorId(operatorId);
                            // 添加素材
                            bannerTemplateService.add(bannerTemplate);
                            boolean iscdnosspen = config.getIscdnossopen();
                            if (iscdnosspen) {
                                uploadListener.addUrl(bannerTemplate.getPath().substring(1), localFile.getPath());
                                Log log = new Log();
                                // 对应模块，这里应该是投放模块
                                log.setModule("BannerTemplate");
                                // 对应的表名，这里是t_adgroup
                                log.setTableName("t_banner_template");
                                // 对应的投放id
                                log.setRecordId(bannerTemplate.getId());
                                // 对应的操作类型
                                log.setActionType("上传");
                                // 变更详情
                                log.setAction("上传了素材:" + bannerTemplate.getId());
                                // 下面这几个字段目前后端数据没有得到。所以仅作测试用！
                                log.setActionTime("100");
                                log.setAccountId(new Long(getLoginUser().getId()));
                                log.setUserIp(Common.toIpAddr(request));
                                log.setAccountName(getLoginUser().getAccountName());
                                logService.add(log);
                            }
                            responseStr = "上传成功";
                        }
                    } else {
                        return "图片尺寸超过2M啦";
                    }
                }
            } catch (IOException e) {
                return "上传失败";
            }
        }
        return responseStr;
    }

    /**
     * 创意导出
     *
     * @param model
     * @param response
     * @param paramMap
     */
    @RequestMapping("/exportBannerReportExcel")
    public void exportBannerReportExcel(HttpServletResponse response, @RequestParam Map<String, Object> paramMap) {
        Map<String, Object> condition = new HashMap<String, Object>();

        Account loginUser = getLoginUser();
        Long agentId = loginUser.getAgentId();
        condition.put("agentId", agentId);
        Long advertiserId = loginUser.getAdvertiserId();

        // 如果账号关联广告主，加入广告主过滤条件
        if (!paramMap.containsKey(advertiserId)) {

            if (advertiserId != 0) {
                condition.put("advertiserId", advertiserId);
            }
        }

        if (paramMap.get("rwidth") != null && paramMap.get("rwidth") != "" && paramMap.get("rheight") != null && paramMap.get("rheight") != "") {
            condition.put("rwidth", Integer.valueOf((String) paramMap.get("rwidth")));
            condition.put("rheight", Integer.valueOf((String) paramMap.get("rheight")));
        }

        if (paramMap.get("type") != null && paramMap.get("type") != "") {
            condition.put("type", Integer.valueOf((String) paramMap.get("type")));
        }
        if (paramMap.get("status") != null && paramMap.get("status") != "") {
            condition.put("status", Integer.valueOf((String) paramMap.get("status")));
        }
        if (paramMap.get("searchValue") != null && paramMap.get("searchValue") != "") {
            condition.put("searchValue", Integer.valueOf((String) paramMap.get("searchValue")));
        }

        // 获取创意的列表
        List<BannerTemplate> bannerTemplateList = bannerTemplateService.findByParams2Ext(condition);
        condition.put("bannerTemplateList", bannerTemplateList);
        response.reset();
        // Content-Type:application/vnd.ms-excel;charset=utf8或者text/xml;charset=utf8
        response.setContentType("application/vnd.ms-excel;charset=utf8");
        // 设置excel文件名称
        SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = "bannerReport" + df2.format(new Date());
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
        // 需要对excel的列的总数进行指定
        int column = 10;
        condition.put("message", "创意导出");
        condition.put("dataSize", (bannerTemplateList.size() + 100));
        condition.put("column", column);
        String excelOrder = templateProcessor.processTemplate("excel/banner.ftl", condition);
        try {
            PrintWriter out = response.getWriter();
            out.write(excelOrder);
            out.flush();
            out.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 上传素材弹窗
     *
     * @param model
     * @param advertiserId
     * @return
     */
    @RequestMapping("openWindow")
    public String toCreateBannerTemplateWin(Model model, long advertiserId) {
        model.addAttribute("advertiserId", advertiserId);
        return page("bannerTemplateWin");
    }

    @RequestMapping("uploadFile")
    public void uploadFile(Model model, HttpServletRequest request) {

    }

}
